package com.example.warehousems.service;

import com.example.warehousems.component.UserInfo;
import com.example.warehousems.dao.MessageRepository;
import com.example.warehousems.dao.model.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MessageService {
    @Autowired
    private MessageRepository messageRepository;

    public List<Message> getAll(Integer userId) {
        return messageRepository.findByUserIdAndIsReadOrderByTimeDesc(userId, 0);
    }

    public List<Message> getAll() {
        return messageRepository.findAllByIsReadOrderByTimeDesc(0);
    }

    public Page<Message> getAllByUserId(int userId, Pageable pageable) {
        return messageRepository.findByUserId(userId, pageable);
    }

    public Page<Message> getAll(Pageable pageable) {
        return messageRepository.findAll(pageable);
    }

    public int markAsRead(Integer id, Integer userId) {
        var message = messageRepository.findById(id).orElseThrow();
        if (!message.getUserId().equals(userId)) {
            return -1;
        }
        message.setIsRead(1);
        messageRepository.save(message);
        return 0;
    }

    public void addMessage(Integer userId, String content, Integer type) {
        // type：0 - controller层调用、 1 - 入库信息、 2 - 出库信息
        var message = new Message();
        message.setUserId(userId);
        message.setContent(content);
        if (type == 0) {
            message.setTitle("测试");
        } else if (type == 1) {
            message.setTitle("入库信息");
        } else if (type == 2) {
            message.setTitle("出库信息");
        }
        message.setType(Message.Type.INFO);
        message.setTime(new java.util.Date().toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDateTime());
        messageRepository.save(message);
    }

    public void markAllAsRead(Integer userId, int[] ids) {
        var messages = messageRepository.findByIdIn(ids);
        for (var message : messages) {
            if (!message.getUserId().equals(userId)) {
                continue;
            }
            message.setIsRead(1);
            messageRepository.save(message);
        }
    }

    public List<Message> getTop(Integer userId) {
        if(UserInfo.get("role").equals("admin"))
            return messageRepository.findTop3ByIsReadOrderByTimeDesc(0);
        return messageRepository.findTop3ByUserIdAndIsReadOrderByTimeDesc(userId, 0);
    }
}
